package network;

import java.util.Hashtable;
import java.util.Vector;

import lib.Core;
import lib.Money;
import lib.TimeStamp;
import lib.XmlPullParser;
import ru.qiwi.lib.UI.ControlEx;
import ru.qiwi.lib.UI.PUIEx;
import ru.qiwi.lib.UI.PageEx;
import Core.Contants;
import Core.DateTimeFormat;
import Core.GlobalData;
import Core.PaymentsLogic;
import DTO.Balance;
import DTO.Good;
import DTO.Group;
import DTO.HeadNumber;
import DTO.ItemGood;
import DTO.Message;
import DTO.OfflinePayment;
import DTO.PriceTypes;
import DTO.Provider;
import DTO.PurchaseOnline;

import android.annotation.SuppressLint;
import com.simpay.cashierandroidapp.R;

@SuppressLint("UseValueOf")
public class ParseXMLProvider {

	int requestResult = 0;
	int actionResult = 0;
	int typeXML;
	Object data;

	public ParseXMLProvider() {
	}

	public ParseXMLProvider(Object data) {
		this.data = data;
	}

	protected int parseGetOfflinePaymentStatus(XmlPullParser xml)
			throws Exception {
		int status = -1;
		while ((typeXML = xml.next()) != XmlPullParser.END_DOCUMENT) {
			if (typeXML == XmlPullParser.START_TAG
					&& "response".equals(xml.getName())) {
				requestResult = Integer.parseInt(xml
						.getAttributeValue("result"));
				// System.out.println("requestResult" + requestResult);
				if (requestResult != 0) {
					throw new Exception("" + requestResult);
				}
			} else if (typeXML == XmlPullParser.START_TAG
					&& "getPaymentStatus".equals(xml.getName())) {
				actionResult = Integer
						.parseInt(xml.getAttributeValue("result"));
				System.out.println("actionResult" + actionResult);
				if (actionResult != 0) {
					throw new Exception("" + actionResult);
				}
			} else if (typeXML == XmlPullParser.START_TAG
					&& "payment".equals(xml.getName())) {
				status = Integer.valueOf(xml.getAttributeValue("status"))
						.intValue();
				int result = Integer.valueOf(xml.getAttributeValue("result"))
						.intValue();
				long id = Long.parseLong(xml.getAttributeValue("id"));
				String date = xml.getAttributeValue("date");
				OfflinePayment op = (OfflinePayment) PaymentsLogic.getIns()
						.findQueue(id);
				if (op != null) {
					op.setStatus(status);
					op.setResult(result);
					if (GlobalData.errCodeTable != null) {
						op.setReason((String) GlobalData.errCodeTable
								.get(new Integer(result)));
					} else {
						// op.setReason(R.get("s1021"));
					}
					if (date != null) {
						op.setDatetime(DateTimeFormat
								.convertGMTtoOtherGMT(date));
						op.setTimestamp(DateTimeFormat.getDate2Long(date));
					} else {
						op.setDatetime(DateTimeFormat.getDateTimeISO(op.getId()));
						op.setTimestamp(DateTimeFormat.getDate2Long(op.getId()));
					}
				}

				if (status == 0) {
					// sau khi parse xong 1 payment, mo payment tiep theo
					LiveThread.send_request = true;

					PaymentsLogic.getIns().moveQueue2ErrorResult(id);
					// AppEntity.event(AppEntity.E_UPDATE_ErrSTATEPAYMENT);
				} else if (status == 1) {
					// AppEntity.event(AppEntity.E_UPDATE_BALANCE);
				} else if (status == 2) {
					// sau khi parse xong 1 payment, mo payment tiep theo
					LiveThread.send_request = true;
					PaymentsLogic.getIns().moveQueue2SuccessResult(id);
					// AppEntity.event(AppEntity.E_UPDATE_SucSTATEPAYMENT, op);
				} else if (status == 3) {
					// sau khi parse xong 1 payment, mo payment tiep theo
					LiveThread.send_request = true;
				}

			}
		}
		LiveThread.send_queue = true;
		return status;
	}

	protected void parseAddOfflinePayment(XmlPullParser xml) throws Exception {
		while ((typeXML = xml.next()) != XmlPullParser.END_DOCUMENT) {
			if (typeXML == XmlPullParser.START_TAG
					&& "response".equals(xml.getName())) {
				requestResult = Integer.parseInt(xml
						.getAttributeValue("result"));
				if (requestResult != 0) {
					throw new Exception("" + requestResult);
				}
			} else if (typeXML == XmlPullParser.START_TAG
					&& "addOfflinePayment".equals(xml.getName())) {
				actionResult = Integer
						.parseInt(xml.getAttributeValue("result"));
				// System.out.println("actionResult" + actionResult);
				if (actionResult != 0) {
					throw new Exception("" + actionResult);
				}
			} else if (typeXML == XmlPullParser.START_TAG
					&& "payment".equals(xml.getName())) {
				long id = Long.parseLong(xml.getAttributeValue("id"));
				int result = Integer.valueOf(xml.getAttributeValue("result"))
						.intValue();
				int status = Integer.valueOf(xml.getAttributeValue("status"))
						.intValue();
				String date = xml.getAttributeValue("date");

				OfflinePayment op = (OfflinePayment) data;// PaymentsLogic.getIns().getLastRequest();
				op.setResult(result);
				op.setStatus(status);
				if (date != null) {
					op.setDatetime(DateTimeFormat.convertGMTtoOtherGMT(date));
					op.setTimestamp(DateTimeFormat.getDate2Long(date));
					if (GlobalData.errCodeTable != null) {
						op.setReason((String) GlobalData.errCodeTable
								.get(new Integer(result)));
					} else {
						// op.setReason(R.get("s1021"));
					}
				} else {
					op.setDatetime(DateTimeFormat.getDateTimeISO(op.getId()));
					op.setTimestamp(DateTimeFormat.getDate2Long(op.getId()));
				}

				if (status == 1 || status == 2) {
					GlobalData.currentBalance = GlobalData.balance.getBalance();
					GlobalData.balance.setBalance(GlobalData.balance
							.getBalance() - op.getFrom() * 100);
					// Core.write(Contants.BALANCE, GlobalData.balance);

					// AppEntity.event(AppEntity.E_SucSENDOFFPAY, op);
					PaymentsLogic.getIns().moveRequestToQueue(id);
					LiveThread.send_queue = true;

					return;
				} else {
					// sau khi parse xong 1 payment, mo payment tiep theo
					LiveThread.send_request = true;

					// AppEntity.event(AppEntity.E_ErrSENDOFFPAY, op);
					PaymentsLogic.getIns().moveRequestToResult(id);
					return;
				}

			}
		}
		LiveThread.send_request = true;
	}

	protected int parseSetPublicKey(XmlPullParser xml) throws Exception {
		while ((typeXML = xml.next()) != XmlPullParser.END_DOCUMENT) {
			if (typeXML == XmlPullParser.START_TAG
					&& "response".equals(xml.getName())) {
				requestResult = Integer.parseInt(xml
						.getAttributeValue("result"));

				// System.out.println("requestResult" + requestResult);
				if (requestResult != 0) {
					// throw new Exception("" + requestResult);
					return requestResult;
				}
			} else if (typeXML == XmlPullParser.START_TAG
					&& "setPublicKey".equals(xml.getName())) {
				xml.next();
				return Integer.parseInt(xml.getAttributeValue("result"));
			}
		}
		return -1;
	}

	protected Balance parseBalance(XmlPullParser xml) throws Exception {
		Balance balance = new Balance();

		while ((typeXML = xml.next()) != XmlPullParser.END_DOCUMENT) {
			if (typeXML == XmlPullParser.START_TAG
					&& "response".equals(xml.getName())) {
				requestResult = Integer.parseInt(xml
						.getAttributeValue("result"));

				// System.out.println("requestResult" + requestResult);
				if (requestResult != 0) {
					throw new Exception("" + requestResult);
				}
			} else if (typeXML == XmlPullParser.START_TAG
					&& "getBalance".equals(xml.getName())) {
				actionResult = Integer
						.parseInt(xml.getAttributeValue("result"));
				// System.out.println("actionResult" + actionResult);
				if (actionResult != 0) {
					throw new Exception("" + actionResult);
				}
			} else if (typeXML == XmlPullParser.START_TAG
					&& "balance".equals(xml.getName())) {
				xml.next();
				balance.setBalance(Money.fromString(xml.getText()));
			} else if (typeXML == XmlPullParser.START_TAG
					&& "tree-balance".equals(xml.getName())) {
				xml.next();
				balance.setTree_balance(Money.fromString(xml.getText()));
			} else if (typeXML == XmlPullParser.START_TAG
					&& "overdraft".equals(xml.getName())) {
				xml.next();
				balance.setOverdraft(Money.fromString(xml.getText()));
			} else if (typeXML == XmlPullParser.START_TAG
					&& "agent-id".equals(xml.getName())) {
				xml.next();
				balance.setAgent_id(Integer.parseInt(xml.getText()));
			}
		}
		return balance;
	}

	//

	protected Vector<Group> parseGroups(XmlPullParser xml) throws Exception {
		Vector<Group> groups = new Vector<Group>();

		while ((typeXML = xml.next()) != XmlPullParser.END_DOCUMENT) {
			if (typeXML == XmlPullParser.START_TAG
					&& "response".equals(xml.getName())) {
				requestResult = Integer.parseInt(xml
						.getAttributeValue("result"));
				// System.out.println("requestResult" + requestResult);
				if (requestResult != 0) {
					throw new Exception("" + requestResult);
				}
			} else if (typeXML == XmlPullParser.START_TAG
					&& "getGroups".equals(xml.getName())) {
				actionResult = Integer
						.parseInt(xml.getAttributeValue("result"));
				// System.out.println("actionResult" + actionResult);
				if (actionResult != 0) {
					throw new Exception("" + actionResult);
				}
			} else if (typeXML == XmlPullParser.START_TAG
					&& "group".equals(xml.getName())) {
				int id = Integer.parseInt(xml.getAttributeValue("id"));
				int parentId = Integer.parseInt(xml
						.getAttributeValue("parentId"));
				int orderId = Integer
						.parseInt(xml.getAttributeValue("orderId"));
				String name = xml.getAttributeValue("name");
				String logo = xml.getAttributeValue("logo");

				Group group = new Group(id, name, orderId, parentId);
				group.setLogo(logo);
				groups.addElement(group);
			}
		}

		return groups;
	} //

	protected Vector<Provider> parseProviders(XmlPullParser xml)
			throws Exception {
		Vector<Provider> vector = new Vector<Provider>();

		while ((typeXML = xml.next()) != XmlPullParser.END_DOCUMENT) {
			if (typeXML == XmlPullParser.START_TAG
					&& "response".equals(xml.getName())) {
				requestResult = Integer.parseInt(xml
						.getAttributeValue("result"));
				// System.out.println("requestResult" + requestResult);
				if (requestResult != 0) {
					throw new Exception("" + requestResult);
				}
			} else if (typeXML == XmlPullParser.START_TAG
					&& "getUIProviders".equals(xml.getName())) {
				actionResult = Integer
						.parseInt(xml.getAttributeValue("result"));
				// System.out.println("actionResult" + actionResult);
				if (actionResult != 0) {
					throw new Exception("" + actionResult);
				}
			} else if (typeXML == XmlPullParser.START_TAG
					&& "provider".equals(xml.getName())) {
				PUIEx pui = PUIEx.from(xml);
				Provider provider = new Provider(
						((PageEx) pui.pages.firstElement()).isOnline, pui.name,
						pui.grpId, pui.id);
				provider.setLogo(pui.logo);

				vector.addElement(provider);
				String text = Contants.pui + provider.getPrv_id();
				Core.writeData(text, pui);
			}
		}
		return vector;
	}

	public void parseMessage(XmlPullParser xml) throws Exception {
		// Core.write(Contants.MESSAGE_CUR, null);
		Vector<Message> mess = new Vector<Message>();
		while ((typeXML = xml.next()) != XmlPullParser.END_DOCUMENT) {
			if (typeXML == XmlPullParser.START_TAG
					&& "response".equals(xml.getName())) {
				requestResult = Integer.parseInt(xml
						.getAttributeValue("result"));
				// System.out.println("requestResult" + requestResult);
				if (requestResult != 0) {
					throw new Exception("" + requestResult);
				}
			} else if (typeXML == XmlPullParser.START_TAG
					&& "getMessages".equals(xml.getName())) {
				actionResult = Integer
						.parseInt(xml.getAttributeValue("result"));
				// System.out.println("actionResult" + actionResult);
				if (actionResult != 0) {
					throw new Exception("" + actionResult);
				}
			} else if (typeXML == XmlPullParser.START_TAG
					&& "row".equals(xml.getName())) {
				Message msg = new Message(xml);

				if (Message.checkForTime(TimeStamp.get(TimeStamp.now(), true),
						msg) && !mess.contains(msg)) {
					mess.add(msg);
				}
			}
		}
		LiveThread.send_mess = true;
		// Core.write(Contants.MESSAGE_CUR, mess);

	}

	@SuppressLint("UseValueOf")
	public Hashtable<Integer, String> parseGetResultCodes(XmlPullParser xml)
			throws Exception {
		Hashtable<Integer, String> res = new Hashtable<Integer, String>();
		while ((typeXML = xml.next()) != XmlPullParser.END_DOCUMENT) {
			if (typeXML == XmlPullParser.START_TAG
					&& "response".equals(xml.getName())) {
				requestResult = Integer.parseInt(xml
						.getAttributeValue("result"));
				// System.out.println("requestResult" + requestResult);
				if (requestResult != 0) {
					throw new Exception("" + requestResult);
				}
			} else if (typeXML == XmlPullParser.START_TAG
					&& "getResultCodes".equals(xml.getName())) {
				actionResult = Integer
						.parseInt(xml.getAttributeValue("result"));
				// System.out.println("actionResult" + actionResult);
				if (actionResult != 0) {
					throw new Exception("" + actionResult);
				}
			} else if (typeXML == XmlPullParser.START_TAG
					&& "row".equals(xml.getName())) {
				int err_id = Integer.parseInt(xml.getAttributeValue("err_id"));
				String err_text = xml.getAttributeValue("err_text");
				// System.out.println(err_id + ":" + err_text);
				res.put(new Integer(err_id), err_text);
			}
		}

		return res;
	}

	public Vector<Good> parseGetNomenclature(XmlPullParser xml)
			throws Exception {
		Vector<Good> nomenClatures = new Vector<Good>();
		while ((typeXML = xml.next()) != XmlPullParser.END_DOCUMENT) {
			if (typeXML == XmlPullParser.START_TAG
					&& "response".equals(xml.getName())) {
				requestResult = Integer.parseInt(xml
						.getAttributeValue("result"));
				// System.out.println("requestResult" + requestResult);
				if (requestResult != 0) {
					throw new Exception("" + requestResult);
				}
			} else if (typeXML == XmlPullParser.START_TAG
					&& "getNomenclature".equals(xml.getName())) {
				actionResult = Integer
						.parseInt(xml.getAttributeValue("result"));
				// System.out.println("actionResult" + actionResult);
				if (actionResult != 0) {
					throw new Exception("" + actionResult);
				}
			} else if (typeXML == XmlPullParser.START_TAG
					&& "goods".equals(xml.getName())) {
				long goods = Money.fromString(xml.getAttributeValue("amount"));
				goods = goods / 100;
				int id = Integer.parseInt(xml.getAttributeValue("id"));
				int currency = Integer.parseInt(xml
						.getAttributeValue("currency"));
				String name = xml.getAttributeValue("name");
				Good good = new Good(goods, id, name, currency);
				nomenClatures.addElement(good);
			}
		}
		return nomenClatures;
	}

	public PurchaseOnline parsePurchaseOnline(XmlPullParser xml)
			throws Exception {

		ItemGood itemGood = new ItemGood();
		PurchaseOnline op = (PurchaseOnline) data;
		while ((typeXML = xml.next()) != XmlPullParser.END_DOCUMENT) {
			if (typeXML == XmlPullParser.START_TAG
					&& "response".equals(xml.getName())) {
				requestResult = Integer.parseInt(xml
						.getAttributeValue("result"));
				// System.out.println("requestResult" + requestResult);
				if (requestResult != 0) {
					throw new Exception("" + requestResult);
				}
			} else if (typeXML == XmlPullParser.START_TAG
					&& "purchaseOnline".equals(xml.getName())) {
				actionResult = Integer
						.parseInt(xml.getAttributeValue("result"));
				// System.out.println("actionResult" + actionResult);
				if (actionResult != 0) {
					throw new Exception("" + actionResult);
				}
			} else if (typeXML == XmlPullParser.START_TAG
					&& "payment".equals(xml.getName())) {
//				long id = Long.parseLong(xml.getAttributeValue("id"));
				int result = Integer.valueOf(xml.getAttributeValue("result"))
						.intValue();
				int status = Integer.valueOf(xml.getAttributeValue("status"))
						.intValue();
				String date = xml.getAttributeValue("date");			

				if (op != null) {
					op.setStatus(status);
					op.setResult(result);
					if (GlobalData.errCodeTable != null) {
						op.setReason((String) GlobalData.errCodeTable
								.get(new Integer(result)));
					} else {
						// op.setReason(R.get("s1021"));
					}
					if (date != null) {
						op.setDatetime(DateTimeFormat
								.convertGMTtoOtherGMT(date));
						op.setTimestamp(DateTimeFormat.getDate2Long(date));
					} else {
						op.setDatetime(DateTimeFormat.getDateTimeISO(op.getId()));
						op.setTimestamp(DateTimeFormat.getDate2Long(op.getId()));
					}

					if (status == 0) {
						// new Exception(Contants.NO_HAVE_PURCHASE);
					}
				}	
			} else if (typeXML == XmlPullParser.START_TAG
					&& "param".equals(xml.getName())) {
				String type = xml.getAttributeValue("name");
				if (type.equals("Pin")) {
					itemGood.setPincode(xml.getValue());
				} else if (type.equals("Cost")) {
					itemGood.setCost(Money.fromString(xml.getValue()));
				} else if (type.equals("%OSMP_UPG_PIN_NOMINALNAME%")) {
					itemGood.setNOMINALNAME(xml.getValue());
				} else if (type.equals("%OSMP_UPG_PIN_SERIAL%")) {
					itemGood.setSERIAL(xml.getValue());
				} else if (type.equals("%OSMP_UPG_PIN_EXPIREDATE%")) {
					itemGood.setEXPIREDATE(xml.getValue());
				}

			}
		}
		op.setItemgood(itemGood);
		return op;

	}

	@SuppressWarnings("unchecked")
	public void parseHeadNumber(XmlPullParser xml) {

		HeadNumber headNumber = null;
		while ((typeXML = xml.next()) != XmlPullParser.END_DOCUMENT) {
			if (typeXML == XmlPullParser.START_TAG
					&& "Provider".equals(xml.getName())) {
				if (headNumber != null) {
					Core.writeData(
							Contants.HEAD_NUMBER + headNumber.getProviderID(),
							headNumber);
				}
				headNumber = new HeadNumber();

				int providerID = Integer.parseInt(xml
						.getAttributeValue("providerID"));
				headNumber.setProviderID(providerID);
			} else if (typeXML == XmlPullParser.START_TAG
					&& "Number".equals(xml.getName())) {
				String hnumber = xml.getAttributeValue("headnumber");
				int type = Integer.parseInt(xml.getAttributeValue("type"));
				headNumber.getHeadnumber().addElement(hnumber);
				headNumber.setType(type);
			}
		}

		if (headNumber != null) {
			Core.writeData(Contants.HEAD_NUMBER + headNumber.getProviderID(),
					headNumber);
		}

	}

	public void parsePriceTypes(XmlPullParser xml) {
		PriceTypes pt;
		while ((typeXML = xml.next()) != XmlPullParser.END_DOCUMENT) {
			if (typeXML == XmlPullParser.START_TAG
					&& "Price".equals(xml.getName())) {
				int providerID = Integer.parseInt(xml
						.getAttributeValue("providerID"));
				String prices = xml.getAttributeValue("prices");
				String[] res = GlobalData.split(prices, ",");
				pt = new PriceTypes(providerID, res);
				Core.writeData(Contants.pricetype + pt.getProviderID(), pt);
			}
		}

	}
	
}
